<template>
  <div id="song-page">
    <div class="left-panel">
      <div class="l-up-panel">
        <div class="tiny-img">
          <img
            alt=""
            :src="'http://localhost:8888' + songData?.tinyImg"
          />
        </div>
        <div class="content">
          <h2>{{ songData?.name }}</h2>
          <p>于{{ songData?.createdAt }}上传</p>
          <p>
            <el-button
              class="button"
              type="primary"
              @click="insertSongsList()"
              >播放
            </el-button>
            <el-button
              class="button"
              type="warning"
              @click="isLoveSong()"
              >{{ isLove ? '收藏' : '取消收藏' }}
            </el-button>
            <el-button
              class="button"
              type="success"
              >下载
            </el-button>
          </p>
          <p><strong>分类:</strong> {{ songData?.genre }}</p>
          <p><strong>作者:</strong> {{ songData?.artist }}</p>
          <p><strong>播放量:</strong> {{ songData?.count }}</p>
        </div>
      </div>
      <div class="l-down-panel">
        <div class="nav"><h2>详细歌词</h2></div>
        <div class="lyric">
          <textarea
            class="textarea"
            :value="textarea"
            disabled
          ></textarea>
        </div>
      </div>
    </div>
    <div class="right-panel">
      <h3>相关推荐</h3>
      <RecommendPanel
        v-for="(item, index) in recommendList"
        :key="index"
        :songVO="item"
        @flesh="initPage"
      ></RecommendPanel>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { onBeforeMount, ref } from 'vue'
import type { UnifyResponse } from '@/types/result'
import type { PageDTO, RecommendSongs, SongsPageDTO, SongsPageInfo, SongsVO } from '@/types/song'
import {
  getIsLoveSongAPI,
  getRecommendSongAPI,
  getSongAPI,
  getUserFavoritesAPI,
  postLoveSongAPI,
  postSongToPlayListAPI,
} from '@/services/songService.ts'
import { useUserStore } from '@/stores/userStore.ts'
import { ElMessage } from 'element-plus'
import RecommendPanel from '@components/RecommendPanel.vue'
import { SortBy, SortOrder } from '@/utils/common/enum.ts'

const route = useRoute()
const songData = ref<SongsVO | null>(null)
const textarea = ref<string>()
const userStore = useUserStore()
const isLove = ref<boolean>(false)
const recommendList = ref<RecommendSongs[]>([])

const insertSongsList = async () => {
  const userStore = useUserStore()
  const existingSong = userStore.songsList.find(item => item.songVO.id === songData.value?.id)
  if (existingSong) {
    userStore.songsListPosition = existingSong.order - 1
    userStore.isOpen = true
    return
  }
  if (songData.value !== null) {
    userStore.songsList.push({
      songVO: songData.value,
      order: userStore.songsList.length + 1,
    })
    userStore.songsListPosition = userStore.songsList.length - 1
    if (userStore.token === null) {
      return
    }
    const res: UnifyResponse<String> = await postSongToPlayListAPI(songData.value!.id)
    console.log(res.data)
    await initUserFavorites()
  }
}

const initUserFavorites = async (page?: number) => {
  try {
    const data: SongsPageInfo = {
      page: page || 1,
      size: 10,
      sortBy: SortBy.CREATED,
      sortOrder: SortOrder.ASC,
    }
    const res: UnifyResponse<PageDTO<SongsPageDTO[]>> = await getUserFavoritesAPI(data)
    if (res.code === 200) {
      useUserStore().favoriteList = res.data || null
    }
  } catch (e) {
    console.error(e)
  }
}

const isLoveSong = async () => {
  if (songData.value && userStore.token) {
    const res = await postLoveSongAPI(songData.value.id)
    isLove.value = !res.data
  } else {
    ElMessage.error('请先登录')
  }
}

const initSongPage = async (id?: number) => {
  try {
    const res: UnifyResponse<SongsVO> = await getSongAPI(id || Number(route.params.id))
    songData.value = res.data
  } catch (e) {
    console.error(e)
  }

  fetch('http://localhost:8888' + songData.value?.lyric)
    .then(response => {
      if (!response.ok) {
        throw new Error('网络请求失败')
      }
      return response.text()
    })
    .then(text => {
      textarea.value = text != '' ? text : '纯音乐'
    })
    .catch(error => {
      console.error('获取文档时出错:', error)
    })
}
const initIsLoveSong = async (id?: number) => {
  try {
    if (songData.value && userStore.token) {
      const res = await getIsLoveSongAPI(id || songData.value.id)
      isLove.value = res.data
    }
  } catch (e) {
    console.error(e)
  }
}
const initRecommend = async (id?: number) => {
  try {
    const res: UnifyResponse<RecommendSongs[]> = await getRecommendSongAPI(id || Number(route.params.id))
    recommendList.value = res.data || []
  } catch (e) {
    console.error(e)
  }
}

const initPage = async (id?: number) => {
  await initSongPage(id)
  await initIsLoveSong(id)
  await initRecommend(id)
}

onBeforeMount(async () => {
  await initPage()
})
</script>

<style scoped>
#song-page {
  width: 70rem;
  height: 67rem;
  margin: 1rem auto;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.left-panel {
  width: 45em;
  height: 100%;
  background: #ff7878;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tiny-img img {
  width: 18em;
  height: 18em;
  background-color: #58a9d1;
}

.left-panel .l-up-panel {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 1.5em;
}

.left-panel .l-up-panel .content {
  display: flex;
  flex-direction: column;
  width: 22em;
  height: 20em;
}

.left-panel .l-up-panel .content p,
h2 {
  margin-top: 1em;
}

.button {
  width: 7em;
  height: 3em;
}

.left-panel .l-down-panel {
  width: 100%;
}

.nav {
  width: 100%;
  height: 5em;
  background-color: #1f9ca6;
  padding: 0.1em 0 0 1em;
}

.right-panel {
  height: 100%;
  width: 24em;
}

.lyric {
  width: 40em;
  margin: 0 auto;
  text-align: center;
}

.textarea {
  width: 30em;
  height: 30em;
  max-width: 30em;
  max-height: 30em;
  min-height: 30em;
  min-width: 30em;
  font-size: 1.5em;
  background-color: #97a373;
  font-weight: bold;
  margin-top: 0.5em;
  padding-left: 3em;
}

::-webkit-scrollbar {
  display: none;
}

textarea::-webkit-resizer {
  background-color: #97a373;
  border: none;
  box-shadow: none;
  display: none;
}

h3 {
  height: 2.5em;
  font-size: 1.5em;
  padding: 0.5em 0 0 1em;
  background-color: #c4f88c;
}
</style>
